package net.thxjj.standard;

import net.util.MD5;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Date;

import static net.util.MD5.fillMD5;

public class TernaryCodeUtil {


    /**
     * CreateDeviceTernary
     * @param devTid
     * @param prodkey
     * @return NewTernary
     */
    public static NewTernary CreateDeviceTernary(String devTid,String prodkey){

        Long time = new Date().getTime();
        String new_token = MD5.get32MD5(devTid+prodkey+String.valueOf(time));
        String new_bindkey =  MD5.get32MD5(prodkey+devTid+String.valueOf(time));
        String new_ctrlkey =  MD5.get32MD5(devTid+String.valueOf(time)+prodkey);

        return new NewTernary(new_token,new_bindkey,new_ctrlkey);
    }


    /**
     * get32MD5
     * @param str
     * @return String
     */
    public static String get32MD5(String str) {
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(str.getBytes());
            // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            String md5=new BigInteger(1, md.digest()).toString(16);
            //BigInteger会把0省略掉，需补全至32位
            return fillMD5(md5);
        } catch (Exception e) {
            throw new RuntimeException("MD5加密错误:"+e.getMessage(),e);
        }
    }

    /**
     * CreateProductKey

     * @return String
     * 生成产品prod_key
     */
    public static String CreateProductKey(){

        Long time = new Date().getTime();
        String new_pro = MD5.get32MD5(String.valueOf(time));

        return new_pro;
    }

    public static void main (String[] args){
        NewTernary newTernary =  TernaryCodeUtil.CreateDeviceTernary("ESP_34ABE","e15ecc3ee7ddc4527885a6576410de86");
        System.out.println(newTernary.getNewBindkey());
        System.out.println(newTernary.getNewCtrlkey());
        System.out.println(newTernary.getNewToken());
    }
}
